from kubernetes import client


class K8S:

    def __init__(self, **kwargs):
        self.configuration = client.Configuration()
        self.client = None
        if kwargs:
            self.init(**kwargs)
        self.client = client.CoreV1Api(client.ApiClient(self.configuration))

    def init(self, host, token):
        self.configuration.host = host
        self.configuration.verify_ssl = False
        self.configuration.api_key = {"authorization": f"Bearer {token}"}


config.kube_config.load_kube_config()
setattr(config.kube_config.Configuration._default, 'verify_ssl', False)

# 获取API的CoreV1Api版本对象
v1 = client.CoreV1Api()

# 列出 namespaces
for ns in v1.list_namespace().items:
    print(ns.metadata.name)

# 列出所有的services
ret = v1.list_service_for_all_namespaces(watch=False)
for i in ret.items:
    print(
        "%s \t%s \t%s \t%s \t%s \n" % (i.kind, i.metadata.namespace, i.metadata.name, i.spec.cluster_ip, i.spec.ports))

# 列出所有的pod
ret = v1.list_pod_for_all_namespaces(watch=False)
for i in ret.items:
    print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))
